package com.micro.frog.acct.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.micro.frog.acct.dao.UserMapper;
import com.micro.frog.acct.dto.UserDTO;
import com.micro.frog.acct.dto.UserDetail;
import com.micro.frog.acct.entity.User;
import com.micro.frog.acct.service.MenuService;
import com.micro.frog.acct.service.UserService;
import com.micro.frog.acct.utils.CacheUtil;
import com.micro.frog.acct.utils.CookieUtil;
import com.micro.frog.acct.vo.UserVO;
import com.micro.frog.core.common.PageResult;
import com.micro.frog.core.common.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author :  ljh
 * @date : 2018/4/10
 **/
@Service
@SuppressWarnings("unchecked")
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    MenuService menuService;
    /**
     * 检查是否已登录
     */
    @Override
    public boolean hasLogin(HttpServletRequest request) {
        String token = CookieUtil.getToken(request);
        return null != CacheUtil.get(token);
    }

    @Override
    public Result login(String loginName, String password, HttpServletRequest request, HttpServletResponse response) {
        User user = new User();
        user.setLoginName(loginName);
        List<User> users = userMapper.selectByCondition(user);
        if (CollectionUtils.isEmpty(users)) {
            return Result.fail("用户名不存在");
        }
        if (users.size() > 1) {
            return Result.fail("登陆账号异常(存在多个)，请联系管理员");
        }
        user = users.get(0);
        if (new Integer(0).equals(user.getStatus())){
            return Result.fail("用户状态锁定，无法登陆");
        }
        if (!password.equals(user.getPassword())) {
            return Result.fail("密码错误");
        }
        updateUserLoginTime(user);
        UserDetail userDetail = new UserDetail();
        userDetail.setId(user.getId());
        userDetail.setLoginName(user.getLoginName());
        userDetail.setUserName(user.getUserName());
        userDetail.setMenus(menuService.userMenus(user));
        String token = CookieUtil.createToken(response);
        CacheUtil.put(token, userDetail);
        return Result.ok(userDetail);
    }

    private void updateUserLoginTime(User user) {
        final Date current = new Date();
        User updateUser = new User();
        updateUser.setId(user.getId());
        if (user.getFirstLoginTime() == null) {
            updateUser.setFirstLoginTime(current);
        }
        updateUser.setLastLoginTime(current);
        userMapper.updateByPrimaryKeySelective(updateUser);
    }

    @Override
    public List<UserVO> all() {
        List<User> list =  userMapper.selectAll();
        List<UserVO> vos = new ArrayList<UserVO>();
        if (!CollectionUtils.isEmpty(list)){
            for (User user : list) {
                UserVO vo = new UserVO();
                BeanUtils.copyProperties(user,vo);
                vos.add(vo);
            }
        }

        return vos;
    }

    @Override
    public PageResult list(UserDTO queryVO) {
        queryVO.init();
        User user = new User();
        BeanUtils.copyProperties(user, queryVO);
        Page page = PageHelper.startPage(queryVO.getPageNum(),queryVO.getPageSize(),true);
        List<User> list = userMapper.selectByCondition(user);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setData(list);
        pageResult.setCode("10000");
        pageResult.setMsg("成功");
        return pageResult;
    }

    @Override
    public Result add(UserVO userVO) {
        User user = new User();
        user.setLoginName(userVO.getLoginName());
        List<User> users = userMapper.selectByCondition(user);
        if (CollectionUtils.isEmpty(users)) {
            return Result.fail("用户名不存在");
        }
        final Date current = new Date();
        BeanUtils.copyProperties(userVO,user);
        user.setCreatedTime(current);
        user.setUpdatedTime(current);
        user.setIsDeleted("N");
        user.setStatus(1);
        userMapper.insertSelective(user);
        return Result.ok("添加成功");
    }

    @Override
    public int delete(Integer id) {
        User user = new User();
        user.setId(id);
        user.setIsDeleted("Y");
        return userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Result update(UserVO userVO) throws Exception {
        User user = userMapper.selectByPrimaryKey(userVO.getId());
        if (user == null) {
            return Result.fail("用户不存在");
        }
        if (!user.getLoginName().equals(userVO.getLoginName())) {
            user = new User();
            user.setLoginName(userVO.getLoginName());
            List<User> list = userMapper.selectByCondition(user);
            if (!CollectionUtils.isEmpty(list)) {
                return Result.fail("登陆名已存在");
            }
        }
        final Date current = new Date();
        BeanUtils.copyProperties(userVO,user);
        user.setUpdatedTime(current);
        int count = userMapper.updateByPrimaryKeySelective(user);
        if (count > 1) {
            throw new Exception("修改失败");
        }
        return Result.ok("修改成功");
    }

    @Override
    public Result updateStatus(User user) throws Exception {

        int count = userMapper.updateByPrimaryKeySelective(user);
        if (count > 1) {
            throw new Exception("修改失败");
        }
        return Result.ok("修改成功");
    }
}
